package com.xtt.dynamic.datasource.config;


import com.xtt.dynamic.datasource.entity.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Component
@Primary    //将该Bean设置为主要注入Bean
public class DynamicDataSource extends AbstractRoutingDataSource {

    //当前使用的数据源标识,用ThreadLocal保持线程安全
    public static ThreadLocal<Operation> name=new ThreadLocal<>();

    //写
    @Autowired
    DataSource dataSource1;

    //读
    @Autowired
    DataSource dataSource2;


    @Override
    protected Object determineCurrentLookupKey() {
        return name.get();
    }

    @Override
    public void afterPropertiesSet() {
        //为targetDataSources初始化所有数据源
        Map<Object,Object> targetDataSources=new HashMap<>();
        targetDataSources.put(Operation.Write,dataSource1);
        targetDataSources.put(Operation.READ,dataSource2);
        super.setTargetDataSources(targetDataSources);

        //为defaultTargetDataSource设置默认数据源
        super.setDefaultTargetDataSource(dataSource1);
        super.afterPropertiesSet();
    }
}
